﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Xml;
using System.IO;
using System.Xml.XPath;
using System.Collections.Generic;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    #region 成员变量

    string middlecontent;//保存XML1
    string resultcontent;//保存XML2
    int bookuuid;  //标示需修改的数据  2008.10.29 add by xiongyan
    BookSystem.BLL.Book bookbll;
    BookSystem.BLL.Book_Class classbll;
    BookSystem.BLL.Book_Language languagebll;

    #endregion

    #region 事件

    /// <summary>
    /// 页面载入
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e) 
    {
        bookbll = new BookSystem.BLL.Book();
        classbll = new BookSystem.BLL.Book_Class();
        languagebll = new BookSystem.BLL.Book_Language();

        this.InitData();
        this.InitCombox(); 
    }

    /// <summary>
    /// 获取图书信息按钮点击
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Btn_ServerClick(object sender, EventArgs e)
    {
        this.Clear();

        if (this.BookExists(this.isbn.Value))
        {
            ClientScript.RegisterStartupScript(Page.GetType(), "e2", "alert('书库中已有这本书！')", true);
            this.GetBookInfoFromDB(this.isbn.Value);
        }
        else
        {
            this.GetBookInfoFromWeb();
        }
    }

    /// <summary>
    /// 点击按钮将记录插入数据库
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSaveInputToDB_Click(object sender, ImageClickEventArgs e)
    {      
        InsertBook();
    }

    /// <summary>
    /// 下载XML按钮点击，存档并下载存档xml文件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        this.Archive();
    }

    #endregion

    #region 图书信息获取

    /// <summary>
    /// 该图书信息是否在access中有记录
    /// </summary>
    /// <param name="isbn">图书ISBN</param>
    /// <example>Response.Write(BookExists(this.isbn.Value).ToString());</example>
    /// <returns>是/否</returns>
    private bool BookExists(string isbn)
    {
        if ((bookbll.GetModelList("isbn='" + isbn + "'")).Count > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    #region GetBookInfoFromWeb 相关方法

    /// <summary>
    /// 从网络获取图书信息并设置控件状态
    /// </summary>
    private void GetBookInfoFromWeb()
    {
        string url = "http://api.douban.com/book/subjects?q=" + isbn.Value;
        this.middlecontent = GetXMLResponse(url);
        this.ObtainValue();
        this.SetValueFromXML(resultcontent);//根据结果XML设置控件状态

    }

    /// <summary>
    /// xiongyan 10.16 0:37 update
    /// 通过URL来获取目标页面的XML代码
    /// </summary>
    /// <param name="url"></param>
    private string GetXMLResponse(string url)
    {
        string content = "";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

        //不维持与服务器的请求状态
        request.KeepAlive = false;
        //创建一个HttpWebRequest对象
        //Assign the response object of HttpWebRequest to a HttpWebResponse variable.\
        HttpWebResponse httpResponse;

        try
        {
            httpResponse = (HttpWebResponse)request.GetResponse();
            //设置页面的编码模式
            System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
            Stream streamResponse = httpResponse.GetResponseStream();
            StreamReader streamRead = new StreamReader(streamResponse, utf8);

            Char[] readBuff = new Char[256];
            //这里使用了StreamReader的Read()方法,参数意指从0开始读取256个char到readByff中.
            //Read()方法返回值为指定的字符串数组,当达到文件或流的末尾使,方法返回0
            int count = streamRead.Read(readBuff, 0, 256);
            while (count > 0)
            {
                String outputData = new String(readBuff, 0, count);
                content += outputData;
                count = streamRead.Read(readBuff, 0, 256);
            }
            streamResponse.Close();
            streamRead.Close();
            httpResponse.Close();
            //Response.Write(content);

            //lance add
            //Session["Content"] = this.content;
            //Session["Length"] = this.content.Length;
            //this.HyperLink1.NavigateUrl = "Save.aspx?name=" + isbn.Value + ".xml";

            return content;

        }
        catch (WebException ex)
        {
            throw new Exception("在请求URL为：" + url + "的页面时产生错误，错误信息为" + ex.ToString());
            return string.Empty;
        }
    }

    /// <summary>
    /// 解析XML
    /// by xiongyan
    /// </summary>
    private void ObtainValue()
    {
        if (string.IsNullOrEmpty(this.middlecontent))
        {
            string url = "http://api.douban.com/book/subjects?q=" + isbn.Value;
            middlecontent = GetXMLResponse(url);
        }
        else
        {
            XmlWriterSettings myXmlSettings = new XmlWriterSettings();
            myXmlSettings.Indent = true;
            myXmlSettings.NewLineOnAttributes = true;
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(this.middlecontent);

                XmlElement root = xmlDoc.DocumentElement;

                XmlNode entrynode = root.ChildNodes[3];
                string url = entrynode.ChildNodes[0].InnerText;
                resultcontent = GetXMLResponse(url);
            }

            catch (Exception ex)
            {
                //Interaction.MsgBox(Err.Description);
            }

            return;
        }
    }

    /// <summary>
    /// 根据最终xml设置控件的状态
    /// by xiongyan
    /// </summary>
    /// <param name="xml"></param>
    private void SetValueFromXML(string xml)
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(xml);

        //XmlNode entrynode1 = xmlDoc.DocumentElement;



        XmlNamespaceManager xnm = new XmlNamespaceManager(xmlDoc.NameTable);

        xnm.AddNamespace("db", "http://www.douban.com/xmlns/");

        XmlNodeList store = xmlDoc.SelectNodes("//db:attribute[@name='price']", xnm);
        if (((store != null)))
        {
            foreach (XmlNode nodeItem in store)
            {
                this.txtPrice.Text = nodeItem.InnerText.ToString();
            }
        }
        XmlNodeList store1 = xmlDoc.SelectNodes("//db:attribute[@name='title']", xnm);
        if (((store1 != null)))
        {
            foreach (XmlNode nodeItem1 in store1)
            {
                this.txtTitle.Text = nodeItem1.InnerText.ToString();
            }
        }
        XmlNodeList store2 = xmlDoc.SelectNodes("//db:attribute[@name='publisher']", xnm);
        if (((store2 != null)))
        {
            foreach (XmlNode nodeItem2 in store2)
            {
                this.txtPublisher.Text = nodeItem2.InnerText.ToString();
            }
        }
        XmlNodeList store3 = xmlDoc.SelectNodes("//db:attribute[@name='pubdate']", xnm);
        if (((store3 != null)))
        {
            foreach (XmlNode nodeItem3 in store3)
            {
                this.txtPublishDate.Text = nodeItem3.InnerText.ToString();
            }
        }
        XmlNodeList store4 = xmlDoc.SelectNodes("//db:attribute[@name='isbn13']", xnm);
        if (((store4 != null)))
        {
            foreach (XmlNode nodeItem4 in store4)
            {
                this.txtISBN.Text = nodeItem4.InnerText.ToString();
            }
        }
        XmlNodeList store5 = xmlDoc.SelectNodes("//db:attribute[@name='author']", xnm);
        string author = "";
        if (((store5 != null)))
        {
            foreach (XmlNode nodeItem5 in store5)
            {
                author += nodeItem5.InnerText.ToString();
            }
            this.txtAuthor.Text = author;
        }
        xnm.AddNamespace("ab", "http://www.w3.org/2005/Atom");
        XmlNodeList store6 = xmlDoc.SelectNodes("//ab:summary", xnm);
        if (((store6 != null)))
        {
            foreach (XmlNode nodeItem6 in store6)
            {
                this.txtContent.Text = nodeItem6.InnerText.ToString();
            }
        }
    }

    #endregion

    #region GetBookInfoFromDB 相关方法

    /// <summary>
    /// 根据access数据库设置控件状态
    /// </summary>
    /// <param name="isbn"></param>
    private void GetBookInfoFromDB(string isbn)
    {
        BookSystem.Model.Book model = this.bookbll.GetModelList("isbn='" + isbn + "'")[0];

        //this.txtPrice.Text = model.price.ToString();        
        this.txtTitle.Text = model.bookname.Trim();
        this.txtPublisher.Text = model.publisher.Trim();
        this.txtPublishDate.Text = model.publishtime.ToLongDateString();
        this.txtISBN.Text = model.isbn.Trim();
        this.txtAuthor.Text = model.author.Trim();
        this.txtContent.Text = model.content.Trim();
        this.ddlClass.Text = classbll.GetModel(model.class_uuid).class_name;
        this.txtPrice.Text = model.price.ToString();
        this.ddlLanguage.SelectedValue = model.book_language;
        this.txtNum.Text = model.booknumber;
            //classbll.GetModel(model.class_uuid).class_other;        
        this.txtBuyDate.Text = model.purchasetime.ToLongDateString();
        this.txtCount.Text = model.purchasecount.ToString();
        //this.CreateNextNumber(this.ddlClass.Text);
        this.bookuuid = model.uuid;
        book_uuid.Value = model.uuid.ToString();
    }

    #endregion

    #endregion

    #region 以前方法

    /// <summary>
    /// 在服务器上保留副本
    /// 即将XML文件保存在网站xml文件夹下
    /// 2008.10.22 by xiongyan
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    //protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    //{
    //    if (string.IsNullOrEmpty(this.middlecontent))
    //    {
    //        string url = "http://api.douban.com/book/subjects?q=" + isbn.Value;
    //        GetXMLResponse(url);
    //    }
    //    XmlDocument xmlDoc = new XmlDocument();
    //    xmlDoc.LoadXml(this.middlecontent);
    //    //保存创建好的XML文档
    //    try
    //    {
    //        xmlDoc.Save(Server.MapPath("xml\\" + isbn.Value + ".xml"));

    //    }
    //    catch (Exception ex)
    //    {
    //        ClientScript.RegisterStartupScript(Page.GetType(), "error", "alert('" + ex.Message + "')", true);
    //    }
    //}


    /// <summary>
    /// 下载XML
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void BtnSave_ServerClick(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(this.middlecontent))
        {
            string url = "http://api.douban.com/book/subjects?q=" + isbn.Value;
            GetXMLResponse(url);
        }

        //StreamReader streamRead = new StreamReader(Server.MapPath("9787115166890.xml"));
        //Char[] readBuff = new Char[256];
        //int count = streamRead.Read(readBuff, 0, 256);
        //while (count > 0)
        //{
        //    String outputData = new String(readBuff, 0, count);
        //    content += outputData;
        //    count = streamRead.Read(readBuff, 0, 256);
        //}
        //streamRead.Close();

        Response.Clear();
        Response.AddHeader("Content-Disposition", "attachment; filename=" + isbn.Value + ".xml");
        Response.AddHeader("Content-Length", this.middlecontent.Length.ToString());
        Response.ContentType = "application/octet-stream";
        Response.Write(this.middlecontent);
        Response.End();
    }


    #endregion

    #region 图书信息插入

    /// <summary>
    /// 插入图书信息
    /// </summary>
    private void InsertBook()
    {
        if (!this.PageValidate())
        {
            return;
        }
        if (book_uuid.Value ==null)
        {
            BookSystem.Model.Book model = new BookSystem.Model.Book();
            //bookbll.GetModel(bookuuid);            
            model.author = this.txtAuthor.Text;
            model.book_language = this.ddlLanguage.SelectedValue;
            model.bookname = this.txtTitle.Text;
            //model.booknumber = this.CreateNextNumber(this.ddlClass.Text);
            model.booknumber = this.txtNum.Text;
            model.content = this.txtContent.Text;
            model.isbn = this.isbn.Value;
            model.price = Convert.ToDouble(this.txtPrice.Text);
            model.publisher = this.txtPublisher.Text;
            model.publishtime = Convert.ToDateTime(this.txtPublishDate.Text);
            model.purchasecount = Convert.ToInt32(this.txtCount.Text);
            model.purchasetime = Convert.ToDateTime(this.txtBuyDate.Text);
            model.class_uuid = classbll.GetID(this.ddlClass.Text);
            model.storefile = string.Empty;

            BookSystem.Model.Book_Class clsmodel = classbll.GetModel(model.class_uuid);
            //clsmodel.class_other = model.booknumber;
            clsmodel.class_other = this.CreateNextNumber(this.ddlClass.Text);

            try
            {
                bookbll.Add(model);
                classbll.Update(clsmodel);
                ClientScript.RegisterStartupScript(Page.GetType(), "ak", "alert('数据保存成功!');", true);
                this.Clear();
            }
            catch (Exception e)
            {
                ClientScript.RegisterStartupScript(Page.GetType(), "aa", "alert('" + e.Message + "');", true);
            }
        }
        else
        {
            int uuid = Convert.ToInt32(book_uuid.Value);
            BookSystem.Model.Book model = bookbll.GetModel(uuid);
            model.author = this.txtAuthor.Text;
            model.book_language = this.ddlLanguage.SelectedValue;
            model.bookname = this.txtTitle.Text;
            model.booknumber = this.CreateNextNumber(this.ddlClass.Text);
            model.booknumber = this.txtNum.Text;
            model.content = this.txtContent.Text;
            model.isbn = this.isbn.Value;
            model.price = Convert.ToDouble(this.txtPrice.Text);
            model.publisher = this.txtPublisher.Text;
            model.publishtime = Convert.ToDateTime(this.txtPublishDate.Text);
            model.purchasecount = Convert.ToInt32(this.txtCount.Text);
            model.purchasetime = Convert.ToDateTime(this.txtBuyDate.Text);
            model.class_uuid = classbll.GetID(this.ddlClass.Text);
            model.storefile = string.Empty;

            BookSystem.Model.Book_Class clsmodel = classbll.GetModel(model.class_uuid);
            clsmodel.class_other = this.CreateNextNumber(this.ddlClass.Text);

            try
            {
                bookbll.Update(model);
                classbll.Update(clsmodel);
                ClientScript.RegisterStartupScript(Page.GetType(), "ak", "alert('数据保存成功!');", true);
                this.Clear();
            }
            catch (Exception e)
            {
                ClientScript.RegisterStartupScript(Page.GetType(), "aa", "alert('" + e.Message + "');", true);
            }
        }
    }

    /// <summary>
    /// 页面信息验证
    /// </summary>
    /// <returns></returns>
    private bool PageValidate()
    {
        try
        {
            Convert.ToDateTime(this.txtPublishDate.Text);
        }
        catch
        {
            ClientScript.RegisterStartupScript(Page.GetType(), "w1", "alert('图书出版日期输入错误，请检查格式');", true);
            return false;
        }

        try
        {
            Convert.ToDateTime(this.txtBuyDate.Text);
        }
        catch
        {
            ClientScript.RegisterStartupScript(Page.GetType(), "w2", "alert('图书购入日期输入错误，请检查格式');", true);
            return false;
        }

        try
        {
            Convert.ToInt32(this.txtCount.Text);
        }
        catch
        {
            ClientScript.RegisterStartupScript(Page.GetType(), "w4", "alert('图书购入总册书格式错误');", true);
            return false;
        }

        try
        {
            Convert.ToDouble(this.txtPrice.Text);
        }
        catch
        {
            ClientScript.RegisterStartupScript(Page.GetType(), "w5", "alert('图书价格格式错误');", true);
            return false;
        }

        if(classbll.GetID(this.ddlClass.Text)==string.Empty)
        {
            ClientScript.RegisterStartupScript(Page.GetType(), "w3", "alert('不存在图书类别：" + this.ddlClass.Text + "');", true);
            return false;
        }

        return true;
    }

    /// <summary>
    /// 根据分类名获取该分类的下一个booknumber
    /// </summary>
    /// <param name="class_name"></param>
    /// <returns></returns>
    private string CreateNextNumber(string class_name)
    {
        string current = classbll.GetModel(classbll.GetID(class_name)).class_other;
        int next = Convert.ToInt32(current.Split('-')[1])+1;
        return current.Split('-')[0] +"-"+ next.ToString();
    }

    #endregion

    #region 数据绑定

    private void InitData()
    {
        //下拉列表的数据绑定
        ////初始化　语种
        System.Data.DataSet ds = (new BookSystem.BLL.Book_Language()).GetAllList();
        ddlLanguage.DataSource = ds.Tables[0];
        ddlLanguage.DataTextField = "language_name";
        ddlLanguage.DataValueField = "uuid";
        ddlLanguage.DataBind();
    }

    /// <summary>
    /// 初始化 分类
    /// </summary>
    private void InitCombox()
    {
        ////初始化　
        StringBuilder returnScript = new StringBuilder();
        returnScript.Append("<script language=\"javascript\">\r\nvar ads = new Array(); var ads2=new Array();\r\n");

        BookSystem.DAL.Book_Class dal = new BookSystem.DAL.Book_Class();

        System.Data.DataSet ds = dal.GetList("");
        int rowsCount = ds.Tables[0].Rows.Count;

        for (int i = 0; i < rowsCount; i++)
        {
           // returnScript.Append("ads[" + i + "]=\"" + ds.Tables[0].Rows[i]["class_name"].ToString() + "\";");
            returnScript.Append("ads2[" + i + "]={code:\"" + ds.Tables[0].Rows[i]["class_other"].ToString() + "\",name:\"" + ds.Tables[0].Rows[i]["class_name"].ToString() + "\"};");
        }
        returnScript.Append("\r\n var dhcomb = new dhCombobox();\r\n  dhcomb.clsName = \"dhcomb\";\r\n  dhcomb.targetObj = document.getElementById(\"" + ddlClass.ClientID + "\");\r\n  dhcomb.arrayData = ads2;\r\n dhcomb.setup();\r\n ads = null;\r\n</script> ");

        string reutrnScript = returnScript.ToString();
        Page.ClientScript.RegisterStartupScript(this.GetType(), "a", reutrnScript);
    }


    #endregion

    #region 存档下载
    /// <summary>
    /// 将access中尚未存档的数据进行存档
    /// 保存成.xml格式到xml文件夹下
    /// 然后再将此次存档的文件标注为已存档
    /// </summary>
    private void Archive()
    {
        DataSet ds = bookbll.GetList("storefile=''");

        if (ds.Tables[0].Rows.Count == 0)
        {
            ClientScript.RegisterStartupScript(Page.GetType(), "e1", "alert('目前所有的数据都已经存档')", true);
            return;
        }

        string filename = DateTime.Now.ToString().Replace(":", "").Replace(" ", "").Replace("-", "");
        try
        {
            ds.WriteXml(Server.MapPath("xml\\" + filename + ".xml"));
        }
        catch 
        {
            ClientScript.RegisterStartupScript(Page.GetType(), "e1", "alert('创建xml存档失败！')", true);
            return;
        }

        List<BookSystem.Model.Book> lst = bookbll.GetModelList("storefile=''");

        foreach (BookSystem.Model.Book model in lst)
        {
            model.storefile = filename;
            bookbll.Update(model);
        }
        ClientScript.RegisterStartupScript(Page.GetType(), "e1", "alert('创建xml存档成功！')", true);

        Response.Redirect("Save.aspx?name=" + filename);
    }

    /// <summary>
    /// 清空
    /// </summary>
    private void Clear()
    {
        this.txtNum.Text = string.Empty;
        this.txtTitle.Text = string.Empty;
        this.txtPublisher.Text = string.Empty;
        this.txtPublishDate.Text = string.Empty;
        this.txtISBN.Text = string.Empty;
        this.txtAuthor.Text = string.Empty;
        this.txtContent.Text = string.Empty;
        this.ddlClass.Text = string.Empty;
        this.txtPrice.Text = string.Empty;
        this.ddlLanguage.SelectedIndex = 0;
        this.txtBuyDate.Text = string.Empty;
        this.txtCount.Text = string.Empty;
        this.isbn.Value = string.Empty;
    }

    #endregion

    protected void BtnClose_ServerClick(object sender, EventArgs e)
    {

    }

    /// <summary>
    /// 取消记录
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
    {
        this.Clear();

    }
}
